package com.wpre.lotterysystem.service.Impl;

import com.wpre.lotterysystem.common.errcode.ServiceErrorCodeConstants;
import com.wpre.lotterysystem.common.exception.ServiceException;
import com.wpre.lotterysystem.common.utils.*;
import com.wpre.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-12-16
 * Time: 19:10
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {


    //对于Redis中的key需要标准化:为了区分业务,需要给key定义一个前缀,例如VerificationCode_13111111111、user_13111111111
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_PREFIX";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;//验证码过期时间60s
    private static final String TEMPLATE_CODE = "SMS_476415094";

    @Autowired
    private SMSUtil smsUtil;


    @Autowired
    private RedisUtil redisUtil;


    /**
     * 发送验证码
     *
     * @param phoneNumber 手机号
     */
    @Override
    public void sendVerificationCode(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_USED_ERROR);
        }
        //2.生成随机验证码
        String code = CaptchaUtil.getCaptcha(4);
        System.out.println("----------------------code--------------:" + code);

        //3.发送验证码
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        smsUtil.sendMessage(TEMPLATE_CODE, phoneNumber, JacksonUtil.writeValueAsString(map));

        //4.缓存验证码(缓存到Redis中)
        redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber, code, VERIFICATION_CODE_TIMEOUT);


    }

    /**
     * 从缓存中获取验证码
     *
     * @return
     */
    @Override
    public String getVerificationCode(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_USED_ERROR);
        }

        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
